package com.examiner.service.impl;

import com.examiner.bean.Manager;
import com.examiner.dao.ManagerDao;
import com.examiner.page.QueryInfo;
import com.examiner.service.ManagerService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.util.List;


@Service
public class ManagerServiceImpl implements ManagerService {

    @Resource
    private ManagerDao managerDao;

    @Override
    public Manager findOne(Integer managerId) {
        return managerDao.getOne(managerId);
    }

    /*
    * 根据用户名查管理员
    * @param: managerUserName
    * @return: Manager
    * */
    @Override
    public Manager findManagerByUserName(String managerUserName) {
        return managerDao.findManagerByUserName(managerUserName);
    }

    //  保存
    @Override
    public void saveManager(Manager manager) {
        Manager save = managerDao.save(manager);
        System.out.println(save);
    }

    // 修改
    @Override
    public void updateManager(Manager manager) {
       managerDao.save(manager);
    }

    // 删除
    @Override
    public void deleteManager(Integer managerId) throws Exception {
        managerDao.deleteById(managerId);
    }

    // 返回分页列表
    @Override
    public List<Manager> getManagerList(QueryInfo queryInfo) {
        // 1. 新建 spec
        Specification spec = new Specification(){
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {
                // 1.获取属性
                Path managerId = root.get("userName");
                // 2. 封装查询条件
                return cb.like(managerId.as(String.class), queryInfo.getQuery()+"%");
            }
        };
        // 2. 新建 pageable
        PageRequest pageRequest = PageRequest.of(queryInfo.getPageNum() - 1, queryInfo.getPageSize(), Sort.Direction.ASC,"id");
        Page<Manager> page = managerDao.findAll(spec, pageRequest);
        System.out.println(page);
        return page.getContent();
    }

    /**
     * 修改密码
     */
    @Override
    public Boolean updateManagerPassword(Integer managerId,String newPassword) {
        int i = managerDao.updatePassword(managerId, newPassword);
        System.out.println(i);
        if (i!= 1) return false;
        return true;
    }

    /**
     * 获取分页总条数
     * @return
     * @param query
     */
    @Override
    public int getTotal(String query) {
        return managerDao.getTotal(query);
    }
}
